/**
 * localStorage存储,
 * 支持过期时间设置, 时间单位为秒
 */
const storage = {
  // 存储
  set(key, value, expire) {
    try {
      const data = {
        value,
        expire: expire ? Date.now() + expire * 1000 : null
      }
      localStorage.setItem(key, JSON.stringify(data))
    } catch (error) {
      console.log('localStorage存储失败:', error);
      // 存储溢出
      if (error.name === 'QuotaExceededError') {
        console.warn('localStorage空间不足，尝试清除过期数据...');
        this.clearExpired()
        // 再次尝试存储
        try {
          this.set(key, value, expire)
        } catch (err) {
          console.error('清理过期数据后，localStorage存储仍然失败:', err);
        }
      }
    }
  },
  // 获取
  get(key, defaultValue = null) {
    try {
      const item = localStorage.getItem(key)
      if (!item) {
        return defaultValue
      }
      const data = JSON.parse(item)
      if (data.expire && data.expire < Date.now()) {
        this.remove(key)
        return defaultValue
      }
      return data.value
    } catch (error) {
      console.error('localStorage获取失败:', error);
      return defaultValue
    }
  },
  // 更新
  update(key, value) {
    const oldData = this.get(key, null)
    if (oldData === null) {
      return false
    }
    this.set(key, value, oldData.expire ? (oldData.expire - Date.now()) / 1000 : null)
    return true
  },
  // 删除
  remove(key) {
    try {
      localStorage.removeItem(key)
    } catch (error) {
      console.error('localStorage删除失败:', error); 
    }
  },
  // 清除所有
  clear() {
    try {
      localStorage.clear()
    } catch (error) {
      console.error('localStorage清空失败:', error); 
    }
  },
  // 清除过期数据
  clearExpired() {
    const keys = Object.keys(localStorage)
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i]
      const item = localStorage.getItem(key)
      const data = JSON.parse(item)
      if (data.expire && data.expire < Date.now()) {
        this.remove(key)
      }
    }
  },
  // 检查是否存在 key 且未过期
  has(key) {
    return this.get(key) !== null
  }
}

export default storage